import SpriteFrame = cc.SpriteFrame;
import MemoryCache from "./MemoryCache";
import UserProfile from "../Domain/UserProfile";

export default class Utils {
    static loadRes<T>(resource: string): Promise<T> {
        return new Promise((resolve, reject) => {
            cc.loader.loadRes(resource, (err: Error, res: any) => {
                if (err) {
                    return reject(err)
                } else {
                    return resolve(res)
                }
            })
        });
    }

    //加载失败也不报异常.返回空值.
    static loadResNoErro<T>(resource: string): Promise<T> {
        return new Promise((resolve, reject) => {
            cc.loader.loadRes(resource, (err: Error, res: any) => {
                if (err) {
                    return resolve(null)
                } else {
                    return resolve(res)
                }
            })
        });
    }

    static animateProgress(progressbar: cc.ProgressBar, progress: number) {
        let oldProgress = progressbar.progress
        if (oldProgress == progress) return
        if (progress > 1) progress = 1
        if (progress < 0) progress = 0
        let delta = progress - oldProgress

        let callback = cc.callFunc(function () {
            //可加可减
            this.progress += delta > 0 ? 0.01 : -0.01
        }.bind(progressbar))
        let action = cc.repeat(cc.sequence(cc.delayTime(0.01), callback), Math.abs(delta / 0.01))
        action.setTag(0)
        progressbar.node.stopActionByTag(0)
        progressbar.node.runAction(action)
    }

    static async loadImage(path: string): Promise<cc.SpriteFrame> {
        if (!path || path.length <= 0) {
            cc.warn("图片加载路径为空,请检查.")
            return Promise.resolve(new cc.SpriteFrame())
        }

        let t = await Utils.loadResNoErro<any>(path)
        let ret: any = t
        if (t instanceof cc.Texture2D) {
            ret = new SpriteFrame(t)
        } else if (t instanceof cc.SpriteFrame) {
        } else {
            t = null
        }
        MemoryCache.instance.put(path, ret)
        return Promise.resolve(ret)
    }

    //获取全局配置.
    static async getGlobalConfig() {
        let configs = null
        try {
            if (CC_DEV) {
                configs = await  Utils.loadRes<any>("/data/config.json")
            } else {
                configs = await Utils.getResFromNet("https://s01.cjyx.appget.cn/res/config.json?_ts=" + Date.now())
            }
        } catch (e) {
            console.error(e)
        }
        return configs
    }

    static previewImage(urls: string[]) {
        if (window.wx) {
            window.wx.previewImage({
                urls: urls || []
            })
        }
    }

    //随机int 值,不包含max
    static randomInt(maxExclude: number = 1): number {
        let c = Math.round(cc.random0To1() * maxExclude)
        if (c >= maxExclude) {
            c = maxExclude - 1
        }
        return c
    }

    //格式化数字,不足10,加0
    static formatNumber(num: number): string {
        return num >= 10 ? `${num}` : `0${num}`
    }

    static async delay(timeSecond: number): Promise<any> {
        return new Promise<any>(resolve => {
            setTimeout(function () {
                resolve()
            }.bind(this), timeSecond * 1000)
        })
    }

    static schedule(interval: number, times: number, callback: Function) {
        if (times <= 1) {
            callback()
            return
        }
        let count = 0
        let timer = setInterval(function () {
            callback()
            if (++count >= times) {
                clearInterval(timer)
            }
        }, interval * 1000)
    }

    //异步动画执行API. 方便链式调用.
    static async runAction(node: cc.Node | cc.Component, action: cc.FiniteTimeAction): Promise<any> {
        if (!action || !node) {
            console.error("runAction param is null:", node, action)
            return
        }
        return new Promise<any>(resolve => {
            let nd = node instanceof cc.Component ? node.node : node
            nd.runAction(cc.sequence(action, cc.callFunc(function () {
                resolve()
            })))
        })
    }

    static async setupShareFunc() {
        if (cc.sys.isObjectValid(window.wx)) {

            let json = await Utils.loadRes<any[]>("data/shares.json")

            if (json && json.length <= 0) {
                console.error("获取分享数据失败.")
                return
            }

            let index = Utils.randomInt(json.length)

            let imgIndex = Utils.randomInt(json[index]["imgs"].length)
            let textIndex = Utils.randomInt(json[index]["txts"].length)

            // console.log("分享图片:", imgIndex, json[index]["imgs"][imgIndex])
            // console.log("分享文字:", textIndex, json[index]["txts"][textIndex])

            let img = `https://s01.cjyx.appget.cn/statics/share/${json[index]["imgs"][imgIndex]}.jpg`
            let txt = json[index]["txts"][textIndex]

            let queryStr = `id=${UserProfile.getProfile().userId}`

            window.wx.showShareMenu({
                withShareTicket: true
            })

            window.wx.onShow(function (launchOptions) {
                console.log("onShow", launchOptions)
                if (launchOptions.shareTicket) {
                    console.log("从群分享中启动.")
                }
            }.bind(this))

            window.wx.onShareAppMessage(function (res) {
                console.log("发起转发:", res)
                // 用户点击了“转发”按钮
                return {
                    title: txt,
                    imageUrl: img,
                    query: queryStr,
                    success: function (ret) {
                        console.log("转发结果:", ret)
                    },
                    fail: function (ret) {
                        console.log("转发失败:", ret)
                    }
                }
            })
        }
    }

    static getResFromNet(pathUrl: string, responseType: string = "text"): Promise<any> {
        return new Promise<any>((resolve, reject) => {
            var xhr = cc.loader.getXMLHttpRequest();
            xhr.open("GET", pathUrl, true);
            xhr.responseType = responseType || "text";

            xhr.setRequestHeader("Access-Control-Allow-Origin", "*")
            xhr.setRequestHeader("Content-Type", "application/json")
            xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest")

            xhr.onload = function (oEvent) {
                var arrayBuffer = xhr.response;
                if (arrayBuffer) {
                    resolve(arrayBuffer)
                } else {
                    reject("请求资源失败")
                }
                console.log("请求资源:", arrayBuffer)
            }
            xhr.onerror = function (oEvent) {
                reject("请求资源失败:" + oEvent)
            }
            xhr.send(null);
        })
    }

    static async sendShareCard(withTicket: boolean = false, queryParams?: string): Promise<any> {

        if (cc.sys.isObjectValid(window.wx)) {
            let json = []

            let index = Utils.randomInt(json.length)

            let imgIndex = Utils.randomInt(json[index]["imgs"].length)
            let textIndex = Utils.randomInt(json[index]["txts"].length)

            let img = `https://s01.cjyx.appget.cn/statics/share/${json[index]["imgs"][imgIndex]}.jpg`
            let txt = json[index]["txts"][textIndex]

            let queryStr = `id=${UserProfile.getProfile().userId}`

            if (queryParams) {
                queryStr += "&"
                queryStr += queryParams
            }

            console.log("sendShareCard,", withTicket)
            window.wx.updateShareMenu({
                withShareTicket: withTicket
            })
            return new Promise<any>(((resolve, reject) => {
                window.wx.shareAppMessage({
                    title: txt,
                    imageUrl: img,
                    query: queryStr,
                    success(res) {
                        //console.log("转发成功!!!", res)
                        resolve(res)
                    },
                    fail(res) {
                        //console.log("转发失败!!!", res)
                        reject(res)
                    }
                })
            }))
        } else {
            return Promise.resolve({shareTickets: {}})
        }
    }

    static showToast(msg: string) {
        if (window.wx) {
            window.wx.showToast({title: msg, duration: 3000})
        }
    }

    static setEnabled(node: cc.Node, enable: boolean) {
        node.opacity = enable ? 255 : 165
    }

    //获取用户头像.
    public static createImage(avatarUrl): Promise<cc.SpriteFrame> {
        // console.log("头像URL:", avatarUrl)
        return new Promise<cc.SpriteFrame>((resolve, reject) => {
            if (window.wx != undefined) {
                try {
                    let image = window.wx.createImage();
                    image.onload = () => {
                        try {
                            let texture = new cc.Texture2D();
                            texture.initWithElement(image);
                            texture.handleLoadedTexture();
                            resolve(new cc.SpriteFrame(texture))
                        } catch (e) {
                            cc.error(e);
                            reject()
                        }
                    };
                    image.src = avatarUrl;
                } catch (e) {
                    cc.log(e);
                    reject()
                }
            } else {
                cc.loader.load({
                    url: avatarUrl, type: 'jpg'
                }, (err, texture) => {
                    if (!err) {
                        resolve(new cc.SpriteFrame(texture))
                    } else {
                        reject()
                    }
                });
            }
        })
    }
}